package es.xpt.ysf.track;

import java.sql.SQLException;
import java.util.Locale;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.jboss.security.SecurityAssociation;

import es.xpt.ysf.configuration.Configuration;
import es.xpt.ysf.configuration.ConfigurationParameterNames;
import es.xpt.ysf.jaas.YSFPrincipal;
import es.xpt.ysf.logging.LogManager;

public class TrackUtils {
	
	public static void track(Track track) {
		TrackDAO dao = null;
	    try {
			dao = getDao(track.getPrincipal());
			dao.insertTrack(track);
	    } catch (Throwable te) {
	    	LogManager.getLog(TrackUtils.class).error(te.getMessage(), te);
	    } finally {
			if (dao != null)
				dao.close();
		}
	}
	
	private static TrackDAO getDao(YSFPrincipal principal) throws NamingException, SQLException {
		YSFPrincipal currentPrincipal = null;
		
		if (principal!=null) {
			currentPrincipal = principal;
		} else {
			currentPrincipal = getTrackPrincipal();
		}
		
		InitialContext ctx = new InitialContext();
		DataSource ds = (DataSource) ctx.lookup(currentPrincipal.getDatasource());
		es.xpt.ysf.dao.Connection ysfConn = new es.xpt.ysf.dao.Connection(ds.getConnection());
		return new TrackDAO(ysfConn, null);
	}
		
	public static YSFPrincipal getTrackPrincipal() {
		YSFPrincipal currentPrincipal = null;
		if (SecurityAssociation.getPrincipal() instanceof YSFPrincipal) {
			currentPrincipal = (YSFPrincipal)SecurityAssociation.getPrincipal();
		} else {
			String userName = SecurityAssociation.getPrincipal().getName();
			Locale locale = new Locale("es", "ES");
			currentPrincipal = new YSFPrincipal(userName);
			currentPrincipal.setUserCode(userName.substring(0, userName.indexOf("@")));
			currentPrincipal.setDescription(userName);
			currentPrincipal.setApplication(userName.substring(userName.indexOf("@") + 1));
			currentPrincipal.setLocale(locale);
			Configuration c = new Configuration(currentPrincipal.getApplication());
			currentPrincipal.setDatasource( c.getString(ConfigurationParameterNames.DATASOURCE) );
		}
		return currentPrincipal;
	}


}
